package cn.xd.itstack.springframework.core.io;

import cn.hutool.core.lang.Assert;
import cn.xd.itstack.springframework.utils.ClassUtil;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Classname ClassPathResource
 * @Description TODO
 * @Date 2022/5/16 上午11:35
 * @Created by lvxiaodong
 */
public class ClassPathResource implements Resource {


    private String classpath;

    private ClassLoader classLoader;
    
    
    
    public ClassPathResource(String classpath){
        this(classpath,null);
    }

    public ClassPathResource(String classpath, ClassLoader classLoader) {
        Assert.notNull(classpath, "Path must not be null");
        this.classpath = classpath;
        this.classLoader = classLoader !=null ?classLoader: ClassUtil.getClassLoader();
    }

    @Override
    public InputStream getInputStream() throws IOException {
        InputStream is = classLoader.getResourceAsStream(this.classpath);
        if (is == null) {
            throw new FileNotFoundException(
                    this.classpath + " cannot be opened because it does not exist");
        }
        return is;
    }
}
